import * as path from "path";
import * as fs from "fs";
import errors from "./error";
import * as yaml from "yaml";

/** Excel 导出配置 */
export interface ExcelExportConfig {
    dataSource: string;
    sheetName: string;
    sourceFile?: string;
    fields: { [key: string]: Column };
    columns: Column[]
}

/** 字段 */
export interface Column {
    title: string,
    format?: string,
    dataField: string,
}



export class Config {
    static getConfigPath() {
        let configsPath = path.join(__dirname, "../configs");
        if (!fs.existsSync(configsPath))
            throw errors.pathNotExists(configsPath);

        return configsPath;
    }

    static getExportConfig(name: string): ExcelExportConfig {
        let configsPath = this.getConfigPath();
        let configFilePath = path.join(configsPath, name + '.yaml');
        if (!fs.existsSync(configFilePath))
            throw errors.pathNotExists(configFilePath);

        let buffer = fs.readFileSync(configFilePath, 'utf-8');
        let config: ExcelExportConfig = yaml.parse(buffer);
        config.columns = [];
        for (let key in config.fields) {
            let field = config.fields[key];
            if (typeof field == 'string') {
                field = { title: field, dataField: key }
            }

            let column: Column = { dataField: key, title: field.title, format: field.format };
            config.columns.push(column);
        }



        return config;
    }
}